package com.jinyang.jetpackdemo.activity

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.content.pm.ActivityInfo
import android.content.res.Configuration
import android.graphics.Bitmap
import android.graphics.PixelFormat
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.text.TextUtils
import android.view.KeyEvent
import android.view.View
import android.view.WindowManager
import android.webkit.WebSettings
import android.widget.RelativeLayout
import androidx.appcompat.app.AppCompatActivity
import com.github.lzyzsd.jsbridge.CallBackFunction
import com.github.lzyzsd.jsbridge.DefaultHandler
import com.jinyang.jetpackdemo.R
import com.jinyang.jetpackdemo.util.LjyLogUtil
import com.jinyang.jetpackdemo.webview.BridgeHelper
import com.jinyang.jetpackdemo.webview.X5JsBridgeWebView
import com.tencent.smtt.export.external.interfaces.IX5WebChromeClient
import com.tencent.smtt.export.external.interfaces.SslError
import com.tencent.smtt.export.external.interfaces.SslErrorHandler
import com.tencent.smtt.sdk.WebChromeClient
import com.tencent.smtt.sdk.WebView
import kotlinx.android.synthetic.main.activity_web_show_pdf.*
import org.json.JSONException
import org.json.JSONObject
import java.util.*

class WebShowPdfActivity : AppCompatActivity() {

    private var bmWebView: X5JsBridgeWebView? = null
    private var loadUrl: String? = null
    private var urlTitle: String? = null
    private var receiveError = false
    private var webChromeClient: WebChromeClient? = null
    private var mCustomView: View? = null
    private var mCustomViewCallback: IX5WebChromeClient.CustomViewCallback? = null
    private var reservationId: String? = null
    private var reservationNo: String? = null
    private var insuranceCategory = 0
    private var reservationStatus: String? = null
    private var show = 0
    private var url: String? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_web_show_pdf)
        initIntent()
        initTitleBar()
        initWebView()
        if (url?.lowercase(Locale.getDefault())?.endsWith(".pdf") == true) {
            bmWebView!!.settings.builtInZoomControls = true
            bmWebView!!.settings.displayZoomControls = false //不显示缩放按钮
            url = "file:///android_asset/index.html?$url"
        }
        bmWebView!!.loadUrl(url)
    }


    @SuppressLint("SetJavaScriptEnabled")
    private fun initWebView() {
        bmWebView = findViewById(R.id.wv_view)
        window.setFormat(PixelFormat.TRANSLUCENT)
        bmWebView!!.view.overScrollMode = View.OVER_SCROLL_ALWAYS
        bmWebView!!.setDefaultHandler(DefaultHandler())
        webChromeClient = object : WebChromeClient() {
            override fun onProgressChanged(view: WebView, newProgress: Int) {
                if (newProgress == 100) {
                    webview_progress.visibility = View.GONE
                } else {
                    webview_progress.visibility = View.VISIBLE
                    webview_progress.progress = newProgress //设置加载进度
                }
                super.onProgressChanged(view, newProgress)
            }

            override fun onReceivedTitle(view: WebView, title: String) {

            }

            override fun onShowCustomView(
                view: View,
                callback: IX5WebChromeClient.CustomViewCallback
            ) {
                LjyLogUtil.d("webAct:onShowCustomView")
                super.onShowCustomView(view, callback)
                activity.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
                bmWebView!!.visibility = View.GONE
                // 如果一个视图已经存在，那么立刻终止并新建一个
                if (mCustomView != null) {
                    callback.onCustomViewHidden()
                    return
                }
                frame_layout.addView(view)
                mCustomView = view
                mCustomView!!.visibility = View.VISIBLE
                mCustomViewCallback = callback
                frame_layout.visibility = View.VISIBLE
                setWebViewExtension(2)
            }

            override fun onHideCustomView() {
                LjyLogUtil.d("webAct:onHideCustomView")
                if (mCustomView == null) {
                    // 不是全屏播放状态
                    return
                }
                bmWebView!!.visibility = View.VISIBLE
                activity.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
                mCustomView!!.visibility = View.GONE
                frame_layout.removeView(mCustomView)
                mCustomView = null
                frame_layout.visibility = View.GONE
                mCustomViewCallback!!.onCustomViewHidden()
                setWebViewExtension(1)
            }
        }
        bmWebView!!.webChromeClient = webChromeClient
        //该方法解决的问题是打开浏览器不调用系统浏览器，直接用webview打开
        bmWebView!!.webViewClient = MyWebViewClient(
            bmWebView!!.bridgeHelper
        )
        bmWebView!!.settings.javaScriptEnabled = true
        //        从Android5.0开始，WebView默认不支持同时加载Https和Http混合模式。加上下面这句代码就好了：
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            bmWebView!!.settings.mixedContentMode = WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE
        }
        bmWebView!!.settings.loadWithOverviewMode = true
        bmWebView!!.settings.defaultTextEncodingName = "UTF-8"
        bmWebView!!.settings.mediaPlaybackRequiresUserGesture = false
        bmWebView!!.settings.useWideViewPort = true
        bmWebView!!.settings.setSupportZoom(true)
        bmWebView!!.settings.layoutAlgorithm =
            com.tencent.smtt.sdk.WebSettings.LayoutAlgorithm.SINGLE_COLUMN
        bmWebView!!.settings.domStorageEnabled = true
        bmWebView!!.settings.cacheMode = WebSettings.LOAD_NO_CACHE
        bmWebView!!.setInitialScale(10)
        // 设置可以访问文件
        bmWebView!!.settings.allowFileAccess = true
        //兼容视频
        setWebViewExtension(1)

//      注册监听方法当js中调用callHandler方法时会调用此方法（handlerName必须和js中相同）
        bmWebView!!.registerHandler("goBack") { data: String?, function: CallBackFunction? -> finish() }

        //PDF下载后跳转手机应用打开
        initDownLoadListener()
        bmWebView!!.registerHandler(
            "openFile"
        ) { data: String?, function: CallBackFunction? ->
            try {
                if (TextUtils.isEmpty(data)) {

                    return@registerHandler
                }
                val jsonObject = JSONObject(data)
                val url = jsonObject.getString("url")
                if (TextUtils.isEmpty(url)) {

                } else if (url.toLowerCase().endsWith(".pdf")) {
                    val intent = Intent(this, WebShowPdfActivity::class.java)
                    intent.putExtra("loadUrl", url)
                    startActivity(intent)
                } else {
                    startAction(activity, url, "")
                }

            } catch (e: JSONException) {
                e.printStackTrace()
            }
        }
    }

    private fun setWebViewExtension(i: Int) {
        try {
            if (bmWebView!!.x5WebViewExtension != null) {
                val data = Bundle()
                data.putBoolean("standardFullScreen", false)
                //true表示标准全屏，false表示X5全屏；不设置默认false，
                data.putBoolean("supportLiteWnd", false)
                //false：关闭小窗；true：开启小窗；不设置默认true，
                data.putInt("DefaultVideoScreen", i)
                //1：以页面内开始播放，2：以全屏开始播放；不设置默认：1
                bmWebView!!.x5WebViewExtension.invokeMiscMethod("setVideoParams", data)
                bmWebView!!.x5WebViewExtension.setScrollBarFadingEnabled(false) //去除滚动条
            }
        } catch (ex: Exception) {
            ex.printStackTrace()
        }
    }


    override fun onConfigurationChanged(config: Configuration) {
        super.onConfigurationChanged(config)
        LjyLogUtil.d("webAct:onConfigurationChanged:" + config.orientation)
        when (config.orientation) {
            Configuration.ORIENTATION_LANDSCAPE -> {
                window.clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN)
                window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN)
                val lp = RelativeLayout.LayoutParams(
                    RelativeLayout.LayoutParams.MATCH_PARENT,
                    RelativeLayout.LayoutParams.WRAP_CONTENT
                )
                lp.setMargins(0, 0, 0, 0)
            }
            Configuration.ORIENTATION_PORTRAIT -> {
                window.clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN)
                window.addFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN)
                val lp2 = RelativeLayout.LayoutParams(
                    RelativeLayout.LayoutParams.MATCH_PARENT,
                    RelativeLayout.LayoutParams.WRAP_CONTENT
                )
                lp2.setMargins(0, 50, 0, 0)
            }
            else -> {}
        }
    }

    /**
     * 全屏时按返加键执行退出全屏方法
     */
    fun hideCustomView() {
        LjyLogUtil.d("webAct:hideCustomView")
        activity.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
        webChromeClient!!.onHideCustomView()
    }

    /**
     * 判断是否是全屏
     */
    fun inCustomView(): Boolean {
        return mCustomView != null
    }

    private val activity: Activity
        private get() = this

    private fun initIntent() {
        val intent = intent
        reservationId = intent.getStringExtra("reservationId")
        reservationNo = intent.getStringExtra("reservationNo")
        reservationStatus = intent.getStringExtra("reservationStatus")
        insuranceCategory = intent.getIntExtra("insuranceCategory", -1)
        show = intent.getIntExtra("show", -1)
        urlTitle = intent.getStringExtra("urlTitle")
        if (!TextUtils.isEmpty(urlTitle)) {
        }
        url = intent.getStringExtra("loadUrl")
    }

    override fun onNewIntent(intent: Intent) {
        super.onNewIntent(intent)
        LjyLogUtil.d("webAct:onNewIntent")
    }

    private fun initTitleBar() {


    }

    private fun goBack() {
        LjyLogUtil.d("webAct:inCustomView=" + inCustomView())
        if (inCustomView()) {
            hideCustomView()
            bmWebView!!.reload()
            return
        }
        if (bmWebView!!.canGoBack()) {
            bmWebView!!.goBack()
        } else {
            finish()
        }
    }

    override fun onPause() {

        super.onPause()
        bmWebView!!.onPause()
    }

    override fun onResume() {
        super.onResume()
        bmWebView!!.onResume()
    }


    override fun onBackPressed() {
        goBack()
        super.onBackPressed()
    }

    public override fun onDestroy() {
        bmWebView!!.destroy()
        super.onDestroy()
    }

    private inner class MyWebViewClient(bridgeHelper: BridgeHelper?) :
        X5JsBridgeWebView.MyWebViewClient(bridgeHelper) {
        // webView默认是不处理https请求的，页面显示空白,
        // onReceivedSslError为webView处理ssl证书设置
        override fun onReceivedSslError(view: WebView, handler: SslErrorHandler, error: SslError) {
            handler.proceed() //忽略 SSL 证书错误
            // handler.cancel();//挂起连接，为默认方式
            // handler.handleMessage(null);
        }

        override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
            try {
                if (url.startsWith("mailto:") || url.startsWith("tel:")) {
                    val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
                    startActivity(intent)
                    return true
                    //                }else if (url.toLowerCase().endsWith(".pdf")){
//                    MyPlanShowPdfActivity.startAction(getActivity(), url);
                }
            } catch (e: Exception) {
                return true
            }
            return super.shouldOverrideUrlLoading(view, url)
        }

        override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
            super.onPageStarted(view, url, favicon)
            LjyLogUtil.d("pageStart")
            receiveError = false
        }

        override fun onPageFinished(view: WebView?, url: String?) {
            super.onPageFinished(view, url)
            if (receiveError) {
                bmWebView!!.visibility = View.GONE
                return
            }
            bmWebView!!.visibility = View.VISIBLE
            loadUrl = url
            LjyLogUtil.d("onPageFinished_url:$url")

        }

        /**
         * 页面加载错误时执行的方法，但是在6.0以下，有时候会不执行这个方法
         */
        override fun onReceivedError(
            view: WebView?,
            errorCode: Int,
            description: String?,
            failingUrl: String?
        ) {
            super.onReceivedError(view, errorCode, description, failingUrl)
            LjyLogUtil.d("onReceivedError: " + errorCode + "_" + description + "_" + failingUrl)
            if (errorCode == -1) {
                return
            }
            receiveError = true
        }
    }

    /**
     * 监听h5中下载文件
     *
     *
     * 代码中只有要下载操作都会回调这个方法，我们只需要添加一个下载方法即可实现
     */
    private fun initDownLoadListener() {
        bmWebView!!.setDownloadListener { url: String, userAgent: String?, contentDisposition: String?, mimetype: String?, contentlength: Long ->
            LjyLogUtil.d(
                "onDownloadStart：$url"
            )
            val intent = Intent(this, WebShowPdfActivity::class.java)
            intent.putExtra("loadUrl", url)
            startActivity(intent)
            //调用H5页面的Loading框隐藏
            bmWebView!!.loadUrl("javascript:hideLoading()")
        }
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            goBack()
            return true
        }
        return super.onKeyDown(keyCode, event)
    }

    companion object {
        fun startAction(activity: Activity, loadUrl: String?, urlTitle: String?, pid: Int) {
            startAction(
                activity, loadUrl, urlTitle, "", "", "",
                -1, 0, pid
            )
        }

        @JvmStatic
        @JvmOverloads
        fun startAction(
            activity: Activity, loadUrl: String?, urlTitle: String?,
            reservationId: String? = "",
            reservationNo: String? = "",
            reservationStatus: String? = "",
            insuranceCategory: Int? =
                -1,
            show: Int = 0,
            pid: Int = 0
        ) {
            val intent = Intent(activity, WebShowPdfActivity::class.java)
            intent.putExtra("loadUrl", loadUrl)
            intent.putExtra("urlTitle", urlTitle)
            intent.putExtra("insuranceCategory", insuranceCategory)
            intent.putExtra("reservationId", reservationId)
            intent.putExtra("reservationNo", reservationNo)
            intent.putExtra("reservationStatus", reservationStatus)
            intent.putExtra("show", show)
            intent.putExtra("pid", pid)
            activity.startActivity(intent)
        }
    }
}